<!--
 * @Description: 
 * @Autor: MQJ
 * @Date: 2021-07-04 10:18:45
 * @LastEditors: MQJ
 * @LastEditTime: 2021-07-06 09:03:23
-->
<template>
  <!-- 提交订单界面 -->

  <div>
    <!-- 顶部 -->
    <div class="header">
      <van-nav-bar
        title="订单确认"
        left-text="返回"
        left-arrow
        @click-left="onClickLeft"
      />
    </div>
    <!-- 中间内容 -->
    <div class="content">
      <!-- 服务地址 -->
      <div class="cell_content">
        <van-cell icon="location-o" @click="getAddressList">
          <!-- 左对齐 -->
          <span class="cell_title">服务地址</span>
          <van-row type="flex" class="cell_row">
            <van-col span="8">姓名：{{ address.name }}</van-col>
            <van-col span="15">电话：{{ address.tel }}</van-col>
          </van-row>
          <van-row type="flex" class="cell_row">
            <van-col span="30">地址：{{ address.address }}</van-col>
          </van-row>
        </van-cell>
      </div>
      <!-- 订单详情 -->
      <div class="cell_content">
        <van-cell icon="balance-list-o">
          <span class="cell_title">订单详情</span>
          <div v-for="(value, key) in orderLines" :key="key">
            <van-row type="flex" v-if="value[1].number != 0" class="cell_row">
              <van-col span="6">{{ value[1].productNmae }}</van-col>
              <van-col span="6">￥{{ value[1].number }}</van-col>
              <van-col span="6">×{{ value[1].price }}</van-col>
            </van-row>
          </div>
          <van-row type="flex" class="cell_row">
            <van-col offset="12" span="12">总价：￥{{ total }}</van-col>
          </van-row>
        </van-cell>
      </div>
      <!-- 服务时间 -->
      <div class="cell_content" @click="isShowTime">
        <van-cell icon="clock-o">
          <span class="cell_title">服务时间</span>
          <span class="cell_row" style="float: right">{{
            currentDate | filter
          }}</span>
        </van-cell>
      </div>
    </div>
    <!-- 确认提交按钮 -->
    <div class="sumbit" @click="sumbitBtn">确认提交</div>
    <!-- 地址选择器 -->
    <van-action-sheet v-model="show" title="选择地址">
      <!-- 需要一个地址选择的列表 -->
      <!-- chosenAddressId 选中的地址id -->
      <!-- :list 地址数据数组 -->
      <!-- @add 点击新增按钮触发的事件 -->
      <!-- @select 切换选中的地址时触发 -->
      <van-address-list
        v-model="chosenAddressId"
        :list="list"
        add-button-text="确定"
        @add="confirmClick"
      />
    </van-action-sheet>

    <!-- 时间选择器 -->
    <van-action-sheet v-model="showTime">
      <van-datetime-picker
        v-model="currentDate"
        type="datetime"
        :min-date="minDate"
        :max-date="maxDate"
        @cancel="cancelTime"
        @confirm="confirmTime"
      />
    </van-action-sheet>

    <!-- 余额不足提示框 -->
    <van-dialog
      @confirm="confirmBalance"
      v-model="showDialog"
      show-cancel-button
      style="font-size: 16px; min-height: 104px"
      ><div class="van-dialog__message">
        当前余额不足，是否充值？
      </div></van-dialog
    >

    <!-- 充值余额 -->
    <van-action-sheet v-model="rechargShow" title="充值">
      <div style="margin: 10px">
        <van-cell-group>
          <van-field
            type="number"
            clearable
            v-model="rechargValue"
            label="充值金额"
            placeholder="请输入充值金额"
          />
        </van-cell-group>
        <div>
          <van-button
            @click="rechargSumbit(rechargValue)"
            round
            block
            style="padding: 10px; background-color: #7879ff; color: #ffffff"
            >提交</van-button
          >
        </div>
      </div>
    </van-action-sheet>
    <div class="footer" style="height: 100px"></div>
  </div>
</template>

<script>
// 引入axios
import { get, post, post_json } from "@/http/axios";
// 引入vuex辅助函数
import { mapActions, mapState, mapGetters, mapMutations } from "vuex";
// 引入时间模块
import moment from "moment";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  props: {},
  data() {
    //这里存放数据
    return {
      // 顾客数据
      customData: [],
      // 是否显示地址选择器
      show: false,
      // 是否显示时间选择器
      showTime: false,
      // 是否显示余额不足提示框
      showDialog: false,
      // 显示充值余额动作面板
      rechargShow: false,
      // 充值金额
      rechargValue: "",
      // 用户金额
      balance: 0,
      // 地址默认值
      chosenAddressId: "",
      // 用于存放地址选择器的数据
      list: [],
      // 用于保存当前用户选择的地址
      address: "",
      // 服务时间
      //时间选择器
      minDate: new Date(2021, 1, 1),
      maxDate: new Date(2025, 10, 1),
      currentDate: new Date(),
      //
      list: [],
      order: [],
      // 充值金额输入框的表单验证
      // rules: [
      //   {
      //     validator: (rechargValue) => {
      //       return /^(?!0)[0-9]{1,3}|1000/.test(rechargValue);
      //     },
      //     message: "单次充值金额不超过1000元",
      //     trigger: "onBlur",
      //   },
      // ],
    };
  },
  //计算属性 类似于data概念
  computed: {
    // 选择购物车的商品信息
    ...mapState("shopcart", ["orderLines"]),
    // 购物车总价格
    ...mapGetters("shopcart", ["total"]),
    ...mapState("user", ["token", "userInfo"]),
    ...mapState("order", ["orderData"]),
    ...mapState("product", ["productData"]),
  },
  //方法集合
  methods: {
    // 引入vuex中的mutations
    ...mapActions("user", ["getUserInfo"]),
    // ...mapActions("order", ["getOrderData"]),
    // 引入购物车模块的的方法
    ...mapMutations("shopcart", ["addShopcart", "clearShopcart"]),
    ...mapActions("order", ["getOrderData"]),
    /**
     * @description: 获取orderLines数据
     * @param {*}
     * @return {*}
     * @author: MQJ
     */
    async getOrderLinesData() {
      let data = {
        page: 1,
        pageSize: 100,
        customerId: this.list.customerId,
      };
      // 调用vuex中的方法 参数
      this.getOrderData(data);
      console.log("-----this.orderData", this.orderData);
      let list = {
        page: 1,
        pageSize: 100,
      };
      let res = await get("/address/pageQuery", list);
      console.log(res.data.data.list);
      this.customData = res.data.data.list;
      for (let index = 0; index < this.customData.length; index++) {
        if (
          this.customData[index].username != null ||
          this.customData[index].telephone != null
        ) {
          let address1 =
            this.customData[index].province +
            this.customData[index].city +
            this.customData[index].area +
            this.customData[index].address;
          this.list.push({
            id: this.customData[index].id,
            name: this.customData[index].username,
            tel: this.customData[index].telephone,
            address: address1,
          });
        }
      }
      this.address = this.list[0];
      return this.list;
    },
    /**
     * @description: 顶部返回操作
     * @param {*}
     * @return {*}
     * @author: MQJ
     */
    onClickLeft() {
      this.$router.go(-1);
    },

    // 控制地址选择弹出框的显示
    getAddressList() {
      // 让action-sheet显示出来
      this.chosenAddressId = this.list[0].id;
      this.show = true;
    },
    // 点击确定按钮触发
    confirmClick() {
      // 将选中的地址赋值给页面上的地址
      this.address = this.list.filter((item) => {
        return item.id === this.chosenAddressId;
      });
      this.show = false;
      this.address = this.address[0];
    },
    isShowTime() {
      this.showTime = true;
    },

    // 时间选择器的取消按钮
    cancelTime() {
      this.showTime = false;
    },
    // 时间选择器的确定按钮
    confirmTime(value) {
      this.currentDate = value;
      this.showTime = false;
    },
    // 提交按钮
    async sumbitBtn() {
      // 通过id获取用户得相关信息
      let res1 = await get("/baseUser/findUserDetailsById", {
        id: this.userInfo.id,
      });
      // 获取用户余额
      this.balance = res1.data.data.balance;
      // console.log("11112222this.userInfo.id", res1.data.data.balance);
      if (this.total != 0 && this.total < this.balance) {
        // console.log("this.orderLines", this.orderLines);
        for (let value of this.orderLines) {
          let productId = value[1].productId;
          let price = value[1].price;
          let number = value[1].number;
          this.order.push({
            id: 0,
            number: number,
            orderId: 0,
            price: price,
            productId: productId,
          });
        }
        // console.log("this.order", this.order);
        let data = {
          addressId: this.address.id,
          customerId: this.userInfo.id,
          orderLines: this.order,
          serviceTime: this.currentDate.getTime(),
        };
        console.log("data", data);
        const res = await post_json("/order/submitOrder", data);
        if (res.data.status === 200) {
          this.$notify({
            message: "提交订单成功",
            type: "success",
          });
          this.clearShopcart();
          setTimeout(() => {
            this.$router.go(-1);
          }, 600);
        } else {
          this.$notify({
            message: res.data.message,
            type: "danger",
          });
        }
      } else {
        if (this.total == 0) {
          this.$notify({
            message: "订单不能为空",
            type: "danger",
          });
        } else {
          this.showDialog = true;
        }
      }
    },
    // 确认充值余额
    confirmBalance() {
      this.rechargShow = true;
    },
    // 充值金额的提交按钮
    async rechargSumbit(value) {
      // console.log(111);
      // console.log("value----", value);
      if (value <= 1000) {
        let res = await get("/account/recharge", {
          customerId: this.userInfo.id,
          money: value,
        });
        if (res.data.status === 200) {
          this.$notify({
            message: "充值成功",
            type: "success",
          });
          this.clearShopcart();
          setTimeout(() => {
            this.$router.go(-1);
          }, 600);
        } else {
          this.$notify({
            message: res.data.message,
            type: "danger",
          });
        }
      } else {
        this.$notify({
          message: "充值金额要小于1000",
          type: "danger",
        });
      }
      this.rechargShow = false;
    },
  },
  filters: {
    filter: function (data) {
      return moment(data).format("YYYY/MM/DD  hh:mm:ss");
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getOrderLinesData();
    this.getUserInfo();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  //监控data中的数据变化
  watch: {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style scoped>
.cell_content {
  margin-bottom: 20px;
  width: 95%;
  border-radius: 15px;
  margin: 10px auto;
  box-shadow: 3px 3px 3px 3px #ece4ff;
}
.cell_title {
  font-size: 16px;
}
.cell_row {
  font-size: 14px;
  color: #cfd0d0;
}
.sumbit {
  width: 53%;
  height: 40px;
  background-image: linear-gradient(90deg, #8b8eec, #b97ee9);
  text-align: center;
  color: #fff;
  border-radius: 22px;
  line-height: 40px;
  margin: 0 auto;
  margin-top: 2em;
  cursor: pointer;
}
.van-icon-edit {
  display: none;
}
.van-dialog__message {
  padding: 26px 24px;
  overflow-y: auto;
  font-size: 14px;
  line-height: 20px;
  text-align: center;
}
</style>
